<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>
        <div class="page-header">
          <a-space>
            <a-button shape="circle" @click="goBack">
              <template #icon><icon-arrow-left /></template>
            </a-button>
            <h2>拣货操作</h2>
          </a-space>
          <div>
            <a-space>
              <a-tag size="medium" color="blue">{{ outboundDetail.code || '-' }}</a-tag>
              <a-tag size="medium" :color="getStatusColor(outboundDetail.status)">
                {{ outboundDetail.status !== undefined ? getStatusText(outboundDetail.status) : '待拣货' }}
              </a-tag>
            </a-space>
          </div>
        </div>
      </template>
      
      <!-- 基础信息区域 -->
      <a-descriptions
        title="基础信息"
        :column="{ xs: 1, sm: 2, md: 3 }"
        :data="basicInfoData"
        :bordered="false"
        size="large"
      />
      
      <a-divider />
      
      <!-- 拣货操作区域 -->
      <div class="picking-area">
        <div class="step-title">商品拣货信息</div>
        
        <a-table
          :data="detailList"
          :loading="loading"
          :pagination="false"
          :bordered="true"
          row-key="id"
          :rowSelection="rowSelection"
          @row-click="(record) => console.log('点击行:', record)"
          @change="() => setTimeout(() => autoRefreshSelection(), 50)"
        >
          <template #columns>
            <a-table-column title="商品编码" data-index="productCode" :width="120" />
            <a-table-column title="商品名称" data-index="productName" :width="180" />
            <a-table-column title="规格型号" data-index="specification" :width="160" />
            <a-table-column title="单位" data-index="unit" :width="80" />
            <a-table-column title="出库数量" data-index="quantity" :width="100" />
            <a-table-column title="库存位置" :width="180">
              <template #cell="{ record }">
                <!-- 改用下拉框选择库位 -->
                <a-select
                  v-model="record.selectedLocation"
                  placeholder="选择库位"
                  style="width: 100%"
                  :disabled="record.picked"
                  @change="(value) => handleLocationChange(record, value)"
                >
                  <a-option
                    v-for="location in record.availableLocations"
                    :key="location.id"
                    :value="location.id"
                    :disabled="!location.hasStock"
                    :label="`${location.name} (可用:${location.available})`"
                  >
                    <template #default>
                      <span :style="{ color: location.hasStock ? 'inherit' : '#ccc' }">
                        {{ location.name }} 
                        <span :style="{ color: location.hasStock ? '#52c41a' : '#f5222d', fontWeight: 'bold' }">
                          (可用:{{ location.available }})
                        </span>
                      </span>
                    </template>
                  </a-option>
                </a-select>
              </template>
            </a-table-column>
            <a-table-column title="实拣数量" :width="150">
              <template #cell="{ record }">
                <a-input-number
                  v-model="record.pickedQuantity"
                  :min="0"
                  :max="record.maxPickable"
                  :disabled="record.picked"
                  @change="(value) => handleQuantityChange(record, value)"
                />
              </template>
            </a-table-column>
            <a-table-column title="差异" :width="100">
              <template #cell="{ record }">
                <span :class="getVarianceClass(record)">{{ getVariance(record) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="备注" :width="200">
              <template #cell="{ record }">
                <a-input
                  v-model="record.remark"
                  placeholder="请输入备注"
                  :disabled="record.picked"
                />
              </template>
            </a-table-column>
            <a-table-column title="状态" :width="100">
              <template #cell="{ record }">
                <a-tag :color="getProductStatusColor(record)">
                  {{ getProductStatusText(record) }}
                </a-tag>
              </template>
            </a-table-column>
            <a-table-column title="操作" :width="120" fixed="right">
              <template #cell="{ record }">
                <a-space>
                  <a-button
                    type="primary"
                    size="small"
                    :disabled="!isPickable(record) || submitting"
                    @click="confirmPick(record)"
                  >
                    确认拣货
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
        
        <div class="action-bar">
          <a-space>
            <a-button
              type="primary"
              :disabled="!hasSelectedItems || submitting"
              @click="batchPick"
            >
              批量确认拣货
            </a-button>
            <a-button
              type="primary"
              status="success"
              :disabled="!canCompletePicking || submitting"
              @click="completePicking"
            >
              完成拣货
            </a-button>
          </a-space>
        </div>
      </div>
    </a-card>
    
    <!-- 操作反馈组件 -->
    <operation-feedback ref="feedbackRef" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Message, Modal } from '@arco-design/web-vue';
import { useOutboundStore } from '@/stores/outbound';
import { useInventoryStore } from '@/stores/inventory';
import { IconArrowLeft, IconLocation, IconSearch, IconRefresh } from '@arco-design/web-vue/es/icon';
import OperationFeedback from '@/components/feedback/OperationFeedback.vue';
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();
const outboundStore = useOutboundStore();
const inventoryStore = useInventoryStore();

const outboundId = route.params.id;
const outboundDetail = ref({});
const detailList = ref([]);
const loading = ref(false);
const locationsLoading = ref(false);
const submitting = ref(false);
const feedbackRef = ref(null);

// 表格选择
const selectedRowKeys = ref([]);
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
  modelValue: selectedRowKeys,
  'onUpdate:modelValue': (val) => {
    console.log('表格选择变化 onUpdate:modelValue:', val);
    selectedRowKeys.value = val;
  },
  // 添加onChange事件处理器
  onChange: (selectedRowKeys, selectedRows) => {
    console.log('表格选择变化 onChange:', selectedRowKeys, selectedRows);
    // 直接触发一次刷新
    setTimeout(() => {
      autoRefreshSelection();
    }, 50);
  },
  // 已拣货的不能选择
  isDisabled: (record) => {
    // 只有确认已拣货的商品不能再选择，其他情况允许选择
    return record.picked === true;
  }
});

// 是否有选中项
const hasSelectedItems = computed(() => {
  // 记录选中数量和状态
  console.log(`当前选中行数: ${selectedRowKeys.value?.length || 0}`, selectedRowKeys.value);
  
  // 只要有选中就返回true，不做其他限制
  return (selectedRowKeys.value?.length || 0) > 0;
});

// 选中项的数量 - 安全访问
const selectedCount = computed(() => {
  return selectedRowKeys.value?.length || 0;
});

// 是否可以完成拣货
const canCompletePicking = computed(() => {
  // 没有商品时不能完成拣货
  if (detailList.value.length === 0) {
    return false;
  }
  
  // 至少有一项已拣货
  const hasPicked = detailList.value.some(item => item.picked);
  
  // 检查是否所有商品都已处理（拣货或状态为异常）
  const allProcessed = detailList.value.every(item => {
    return item.picked || item.status === 0 || item.status === 'exception';
  });
  
  const result = hasPicked && allProcessed;
  console.log('完成拣货按钮状态:', { hasPicked, allProcessed, result });
  
  return result;
});

// 状态辅助函数
const getStatusColor = (status) => {
  return outboundStore.getOutboundStatusColor(status);
};

const getStatusText = (status) => {
  return outboundStore.getOutboundStatusText(status);
};

// 商品状态函数
const getProductStatusColor = (record) => {
  if (record.picked) return 'green';
  if (record.status === 0) return 'red';     // 已取消
  if (record.status === 1) return 'orange';  // 待拣货
  if (record.status === 2) return 'blue';    // 待发货 
  if (record.status === 3) return 'green';   // 已完成
  return 'orange';  // 默认为待拣货颜色
};

const getProductStatusText = (record) => {
  if (record.picked) return '已拣货';
  if (record.status === 0) return '已取消';
  if (record.status === 1) return '待拣货';
  if (record.status === 2) return '待发货';
  if (record.status === 3) return '已完成';
  return '待拣货';  // 默认状态
};

// 计算差异并设置样式类
const getVariance = (record) => {
  const variance = record.pickedQuantity - record.quantity;
  return variance > 0 ? `+${variance}` : variance;
};

const getVarianceClass = (record) => {
  const variance = record.pickedQuantity - record.quantity;
  if (variance < 0) return 'text-danger';
  if (variance > 0) return 'text-success';
  return '';
};

// 设置基础信息
const basicInfoData = computed(() => {
  if (!outboundDetail.value) return [];
  
  const typeMap = { 1: '销售出库', 2: '退货出库', 3: '其他出库' }; 
  const displayValue = (value) => value ? value : '-';

  return [
    { label: '出库单号', value: displayValue(outboundDetail.value.code) }, 
    { label: '客户', value: displayValue(outboundDetail.value.customer?.name) }, 
    { label: '仓库', value: displayValue(outboundDetail.value.warehouse?.name) }, 
    { label: '出库类型', value: typeMap[outboundDetail.value.type] || `未知 (${outboundDetail.value.type})` }, 
    { label: '创建时间', value: outboundDetail.value.created_at ? dayjs(outboundDetail.value.created_at).format('YYYY-MM-DD HH:mm:ss') : '-' } 
  ];
});

// 是否可以拣货
const isPickable = (record) => {
  // 记录判断过程，方便调试
  const reasons = [];
  
  // 如果商品已拣货，则不能再次拣货
  if (record.picked) {
    reasons.push('已拣货');
    return false;
  }
  
  // 拣货数量必须大于0，但不强制小于最大可拣数量(在批量拣货时处理)
  if (!record.pickedQuantity || record.pickedQuantity <= 0) {
    reasons.push('拣货数量必须大于0');
    return false;
  }
  
  // 只有单个商品拣货时才判断库位，批量拣货会自动处理库位选择
  if (!record.selectedLocation && !record.availableLocations?.length) {
    reasons.push('无可用库位');
    return false;
  }
  
  // 记录日志(如果有问题)
  if (reasons.length > 0) {
    console.log(`商品 ${record.productName} 不可拣货原因:`, reasons);
  }
  
  return true;
};

// 处理数量变化
const handleQuantityChange = (record, value) => {
  record.pickedQuantity = value;
  
  // 自动标记状态
  if (value === 0) {
    record.status = 0;  // 0=已取消（异常）
  } else if (value !== record.quantity) {
    record.status = 1;  // 1=待拣货（数量差异）
  } else {
    record.status = 2;  // 2=待发货（正常）
  }
};

// 返回上一页
const goBack = () => {
  router.push('/outbound/orders');
};

// 加载商品库存位置信息
const loadProductLocations = async () => {
  try {
    locationsLoading.value = true;
    for (const item of detailList.value) {
      // productId should be available here due to previous mapping
      if (!item.productId) { 
          console.warn("Missing productId for item:", item);
          item.availableLocations = [];
          item.maxPickable = 0;
          item.pickedQuantity = 0;
          item.status = 0;  // 0=已取消（异常）
          continue; // Skip if no productId
      }
      
      // 获取库位数据
      const inventoryData = await inventoryStore.getProductLocations(item.productId);
      console.log("原始库位数据:", inventoryData);
      
      if (inventoryData && inventoryData.length > 0) {
        // 合并相同库位的数据，防止重复显示
        const locationMap = new Map();
        
        // 首先按库位ID分组并合计可用数量
        inventoryData.forEach(location => {
          const locationId = location.location_id;
          const available = Number(location.quantity || 0) - Number(location.lock_stock || 0);
          
          if (locationMap.has(locationId)) {
            // 已存在该库位，累加可用数量
            const existingLoc = locationMap.get(locationId);
            existingLoc.available += available;
          } else {
            // 新的库位，添加到Map
            locationMap.set(locationId, {
              id: locationId,
              name: location.location?.code || "未知库位", 
              available: available,
              code: location.location?.code || "未知库位",
              // 添加库存状态信息
              hasStock: available > 0,
              location: location.location
            });
          }
        });
        
        // 转换Map为数组
        const mergedLocations = Array.from(locationMap.values());
        console.log("合并后的库位数据:", mergedLocations);
        
        // 按可用库存量降序排序，但保留所有库位（包括无库存的）
        item.availableLocations = mergedLocations.sort((a, b) => {
          // 首先按是否有库存排序
          if (a.hasStock && !b.hasStock) return -1;
          if (!a.hasStock && b.hasStock) return 1;
          // 然后按库存量排序
          return b.available - a.available;
        });
        
        console.log(`商品 ${item.productName} 的可用库位:`, item.availableLocations);
        
        // 只有有库存的库位才能用于默认选择
        const availableLocations = item.availableLocations.filter(loc => loc.hasStock);
        
        if (availableLocations.length > 0) {
          // 自动选择第一个有库存的库位
          const defaultLocation = availableLocations[0];
          item.selectedLocation = defaultLocation.id;
          item.maxPickable = defaultLocation.available;
          
          // 准备显示信息
          item.selectedLocationInfo = {
            id: defaultLocation.id,
            name: defaultLocation.name,
            available: defaultLocation.available
          };
          
          // 如果商品尚未拣货，则使用出库数量作为实拣数量的默认值
          // 但不要超过最大可拣数量
          if (!item.picked) {
            item.pickedQuantity = Math.min(item.quantity, item.maxPickable);
          }
          
          item.status = item.pickedQuantity === item.quantity ? 2 : 1; // 2=待发货（正常）, 1=待拣货（数量差异）
        } else {
          // 无可用库存
          item.maxPickable = 0;
          if (!item.picked) {
            item.pickedQuantity = 0;
          }
          item.status = 0;  // 0=已取消（异常）
        }
      } else {
        item.availableLocations = [];
        item.maxPickable = 0;
        if (!item.picked) {
          item.pickedQuantity = 0;
        }
        item.status = 0;  // 0=已取消（异常）
      }
    }
  } catch (error) {
    console.error('加载库存位置信息失败:', error);
    Message.error('加载库存位置信息失败');
  } finally {
    locationsLoading.value = false;
  }
};

// 监听库位选择变化
const handleLocationChange = (record, locationId) => {
  if (!locationId) return;
  
  console.log(`库位选择变更: 商品=${record.productName}, 库位ID=${locationId}`);
  
  // 找到对应库位的可用库存
  const location = record.availableLocations.find(loc => loc.id === locationId);
  if (location) {
    // 更新最大可拣数量
    record.maxPickable = location.available;
    
    // 更新显示信息
    record.selectedLocationInfo = {
      id: location.id,
      name: location.name,
      available: location.available
    };
    
    // 自动调整拣货数量不超过最大可拣货数量
    if (record.pickedQuantity > record.maxPickable) {
      record.pickedQuantity = record.maxPickable;
    } else if (!record.picked && (!record.pickedQuantity || record.pickedQuantity === 0)) {
      // 如果商品尚未拣货且拣货数量为0，则设置默认值
      record.pickedQuantity = Math.min(record.quantity, record.maxPickable);
    }
    
    // 更新状态
    if (record.pickedQuantity === 0) {
      record.status = 0; // 已取消
    } else if (record.pickedQuantity === record.quantity) {
      record.status = 2; // 待发货（数量匹配）
    } else {
      record.status = 1; // 待拣货（数量不匹配）
    }
    
    console.log(`库位已更新: ${location.name}, 最大可拣=${location.available}, 实拣=${record.pickedQuantity}, 状态=${record.status}`);
  }
};

// 添加全局加载消息ID跟踪
const activeLoadingMessageIds = ref([]);

// 辅助函数：显示加载消息并跟踪ID
const showLoadingMessage = (content, duration = 0) => {
  // 确保先清除之前可能存在的同内容消息
  const existingMsgs = activeLoadingMessageIds.value.filter(id => 
    id.includes(content.replace(/\s+/g, '_').substring(0, 20))
  );
  
  existingMsgs.forEach(id => {
    clearLoadingMessage(id);
  });

  // 生成包含内容信息的唯一ID，便于识别
  const contentKey = content.replace(/\s+/g, '_').substring(0, 20);
  const id = `loading_${contentKey}_${Date.now()}`;
  
  Message.loading({
    content: content,
    duration: duration, // 如果设置了duration>0，消息会自动关闭
    id: id
  });
  
  activeLoadingMessageIds.value.push(id);
  
  // 如果设置了duration>0，在duration后自动从跟踪列表中移除
  if (duration > 0) {
    setTimeout(() => {
      clearLoadingMessage(id);
    }, duration);
  }
  
  return id;
};

// 辅助函数：清除特定加载消息
const clearLoadingMessage = (id) => {
  if (id) {
    Message.clear(id);
    activeLoadingMessageIds.value = activeLoadingMessageIds.value.filter(msgId => msgId !== id);
  }
};

// 辅助函数：清除所有加载消息
const clearAllLoadingMessages = () => {
  activeLoadingMessageIds.value.forEach(id => {
    Message.clear(id);
  });
  activeLoadingMessageIds.value = [];
};

// 组件卸载前清除所有加载消息
onBeforeUnmount(() => {
  clearAllLoadingMessages();
});

// 添加定时器引用，用于清理
let selectionCheckTimer = null;

// 自动检测选择状态变化
const startAutoSelectionCheck = () => {
  // 先清除可能存在的定时器
  if (selectionCheckTimer) {
    clearInterval(selectionCheckTimer);
  }
  
  // 设置定时器，每500ms检查一次选择状态
  selectionCheckTimer = setInterval(() => {
    // 检查页面中的复选框状态
    const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
    const tableCheckboxes = Array.from(checkboxes).filter(cb => 
      cb.closest('table') && !cb.closest('th') // 排除表头的全选框
    );
    
    // 如果选中数量与当前记录不一致，尝试更新
    if (tableCheckboxes.length !== selectedCount.value) {
      console.log('检测到选择状态变化，自动更新');
      autoRefreshSelection(); // 调用静默刷新
    }
  }, 500);
};

// 确保selectedRowKeys总是数组
const ensureSelectedKeysIsArray = () => {
  if (!Array.isArray(selectedRowKeys.value)) {
    console.warn('selectedRowKeys不是数组，重置为空数组');
    selectedRowKeys.value = [];
  }
};

// 静默刷新选择状态(不显示消息)
const autoRefreshSelection = () => {
  console.log('自动刷新选择状态...');
  
  // 确保selectedRowKeys.value是数组
  ensureSelectedKeysIsArray();
  
  // 检查DOM中实际选中的checkbox
  const checkboxes = document.querySelectorAll('table input[type="checkbox"]:checked');
  console.log('表格中选中的checkbox数量:', checkboxes.length);

  // 获取所有行(除表头外)
  const rows = document.querySelectorAll('table tbody tr');
  console.log('表格总行数:', rows.length);
  
  // 收集选中的行ID
  const selectedIds = [];
  let foundCheckedRows = false;
  
  // 遍历表格行
  rows.forEach((row, index) => {
    // 获取行中的复选框
    const checkbox = row.querySelector('input[type="checkbox"]');
    // 如果复选框被选中且索引在有效范围内
    if (checkbox?.checked && index < detailList.value.length) {
      foundCheckedRows = true;
      const item = detailList.value[index];
      if (item && item.id) {
        selectedIds.push(item.id);
        console.log(`检测到第${index+1}行被选中，ID:`, item.id);
      }
    }
  });
  
  // 如果找不到选中的行但有选中的复选框，可能是DOM结构与预期不符
  if (checkboxes.length > 1 && !foundCheckedRows) {
    console.warn('发现选中的复选框但未找到对应的行，尝试备用方法');
    
    // 备用方法：直接从复选框推断行索引
    // 跳过第一个(通常是表头的全选框)
    for (let i = 1; i < checkboxes.length; i++) {
      const rowIndex = i - 1;
      if (rowIndex < detailList.value.length) {
        const item = detailList.value[rowIndex];
        if (item && item.id) {
          selectedIds.push(item.id);
          console.log(`备用方法：检测到第${rowIndex+1}行被选中，ID:`, item.id);
        }
      }
    }
  }
  
  // 只在有变化时更新
  console.log('当前已选择:', selectedRowKeys.value);
  console.log('检测到的选择:', selectedIds);
  
  if (JSON.stringify(selectedIds.sort()) !== JSON.stringify([...selectedRowKeys.value].sort())) {
    console.log('更新选择状态:', selectedIds);
    selectedRowKeys.value = selectedIds;
    
    // 为选中的商品自动选择库位和设置拣货数量
    for (const itemId of selectedIds) {
      const record = detailList.value.find(item => item.id === itemId);
      if (!record) continue;
      
      // 如果没有选择库位，自动选择第一个有库存的库位
      if (!record.selectedLocation && record.availableLocations && record.availableLocations.length > 0) {
        const availableLoc = record.availableLocations.find(loc => loc.hasStock);
        if (availableLoc) {
          console.log(`自动为商品 ${record.productName} 选择库位:`, availableLoc);
          record.selectedLocation = availableLoc.id;
          record.maxPickable = availableLoc.available;
          
          // 如果拣货数量未设置或为0，设置为订单数量与可用数量的较小值
          if (!record.pickedQuantity || record.pickedQuantity <= 0) {
            record.pickedQuantity = Math.min(record.quantity, availableLoc.available);
            console.log(`自动设置商品 ${record.productName} 拣货数量:`, record.pickedQuantity);
          }
        }
      }
    }
  }
};

// 确认拣货一个商品
const confirmPick = async (record) => {
  if (!isPickable(record)) {
    Message.warning('请选择库位并输入拣货数量');
    return;
  }
  
  // 先清除可能存在的加载消息
  clearAllLoadingMessages();
  
  // 生成唯一的消息ID
  const loadingMsgId = showLoadingMessage('正在处理拣货请求...', 2000);
  
  try {
    // 确认对话框
    const confirmResult = await feedbackRef.value.showConfirm({
      title: '确认拣货',
      content: `确认从库位 ${getLocationNameById(record.selectedLocation)} 拣货 ${record.pickedQuantity} ${record.unit} ${record.productName}？`,
      icon: 'icon-info',
      iconColor: '#165DFF'
    });
    
    if (!confirmResult) {
      clearLoadingMessage(loadingMsgId);
      return;
    }
    
    submitting.value = true;
    
    // 构造拣货数据
    const pickItem = {
      detailId: record.id,
      locationId: record.selectedLocation,
      pickedQuantity: record.pickedQuantity,
      remark: record.remark || ''
    };
    
    // 调用API进行拣货
    const result = await outboundStore.pickOutbound(outboundId, { details: [pickItem] });
    
    // 清除加载消息
    clearLoadingMessage(loadingMsgId);
    
    if (result) {
      record.picked = true;
      
      // 直接显示简单的成功消息
      Message.success(`成功拣货 ${record.pickedQuantity} ${record.unit} ${record.productName} 从 ${getLocationNameById(record.selectedLocation)}`);
      
      // 重新获取出库单详情 - 恢复调用以获取最新状态
      await getOutboundDetail(); 
    }
  } catch (error) {
    console.error('拣货失败:', error);
    
    // 清除加载消息
    clearLoadingMessage(loadingMsgId);
    clearAllLoadingMessages();
    
    // 显示错误结果
    feedbackRef.value.showResult({
      status: 'error',
      title: '拣货失败',
      message: '商品拣货失败',
      description: '操作过程中发生错误，请重试',
      primaryAction: {
        text: '重试',
        callback: () => confirmPick(record)
      },
      secondaryAction: {
        text: '关闭',
        callback: () => {}
      }
    });
  } finally {
    submitting.value = false;
  }
};

// 批量拣货相关功能
const batchPick = async () => {
  // 检查选中行数量并记录日志
  console.log('当前选中的行数:', selectedCount.value);
  console.log('选中的商品ID:', selectedRowKeys.value || []);
  console.log('所有商品数据:', detailList.value);
  
  // 检查是否有元素被选中但selectedRowKeys为空的情况
  const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
  console.log('页面中实际选中的checkbox数量:', checkboxes.length);
  
  // 尝试直接获取表格选中状态
  if (selectedCount.value === 0 && checkboxes.length > 0) {
    console.log('警告: 检测到DOM中有选中项但selectedRowKeys为空，尝试修复...');
    // 查找表格并获取选中的行
    const selectedRows = detailList.value.filter((_, index) => {
      return checkboxes[index+1]?.checked; // +1 是因为第一个checkbox可能是全选
    });
    if (selectedRows.length > 0) {
      console.log('找到选中行:', selectedRows);
      selectedRowKeys.value = selectedRows.map(row => row.id);
    }
  }
  
  if (!selectedCount.value) {
    Message.warning('请选择至少一个商品进行拣货');
    return;
  }
  
  // 批量设置所有选中项的库位和拣货数量（如果未设置）
  for (const itemId of selectedRowKeys.value) {
    const record = detailList.value.find(item => item.id === itemId);
    if (!record) continue;
    
    // 如果没有选择库位，自动选择第一个有库存的库位
    if (!record.selectedLocation && record.availableLocations && record.availableLocations.length > 0) {
      const availableLoc = record.availableLocations.find(loc => loc.hasStock);
      if (availableLoc) {
        console.log(`自动为商品 ${record.productName} 选择库位:`, availableLoc);
        record.selectedLocation = availableLoc.id;
        record.maxPickable = availableLoc.available;
        
        // 如果拣货数量未设置或为0，设置为订单数量与可用数量的较小值
        if (!record.pickedQuantity || record.pickedQuantity <= 0) {
          record.pickedQuantity = Math.min(record.quantity, availableLoc.available);
          console.log(`自动设置商品 ${record.productName} 拣货数量:`, record.pickedQuantity);
        }
      }
    }
  }

  // 先清除可能存在的加载消息
  clearAllLoadingMessages();

  try {
    // 检查所选商品的状态，筛选出可以拣货的商品
    const validItems = [];
    const invalidItems = [];
    
    selectedRowKeys.value.forEach(itemId => {
      const record = detailList.value.find(i => i.id === itemId);
      if (!record) {
        console.warn(`未找到ID为${itemId}的商品记录`);
        invalidItems.push({ id: itemId, reason: '记录不存在' });
        return;
      }
      
      // 确保每个选中的商品都有库位信息和有效的拣货数量
      if (!record.selectedLocation) {
        console.warn(`商品 ${record.productName} 未选择库位`);
        if (record.availableLocations && record.availableLocations.length > 0) {
          // 自动选择第一个有库存的库位
          const availableLoc = record.availableLocations.find(loc => loc.hasStock);
          if (availableLoc) {
            record.selectedLocation = availableLoc.id;
            record.maxPickable = availableLoc.available;
            if (!record.pickedQuantity || record.pickedQuantity <= 0) {
              record.pickedQuantity = Math.min(record.quantity, availableLoc.available);
            }
            validItems.push(record);
            return;
          }
        }
        invalidItems.push({ id: itemId, name: record.productName, reason: '未选择库位' });
        return;
      }
      
      if (!record.pickedQuantity || record.pickedQuantity <= 0 || 
          (record.maxPickable > 0 && record.pickedQuantity > record.maxPickable)) {
        console.warn(`商品 ${record.productName} 拣货数量无效`);
        invalidItems.push({ 
          id: itemId, 
          name: record.productName, 
          reason: '拣货数量无效',
          current: record.pickedQuantity,
          max: record.maxPickable
        });
        return;
      }
      
      validItems.push(record);
    });
    
    // 检查有效商品数量
    if (validItems.length === 0) {
      if (invalidItems.length > 0) {
        let msg = '所选商品存在以下问题，无法拣货:\n';
        invalidItems.slice(0, 3).forEach(item => {
          msg += `- ${item.name || '未知商品'}: ${item.reason}\n`;
        });
        if (invalidItems.length > 3) {
          msg += `以及其他 ${invalidItems.length - 3} 个问题...`;
        }
        Message.warning(msg);
      } else {
        Message.warning('没有可拣货的商品，请确保选择库位和输入有效拣货数量');
      }
      return;
    }
    
    if (invalidItems.length > 0) {
      const confirmResult = await feedbackRef.value.showConfirm({
        title: '部分商品无法拣货',
        content: `已选 ${selectedRowKeys.value.length} 项商品中，有 ${invalidItems.length} 项不符合拣货条件，是否仅对 ${validItems.length} 项有效商品进行拣货？`,
        icon: 'icon-warning',
        iconColor: '#FF7D00'
      });
      
      if (!confirmResult) return;
    } else {
      // 弹出确认对话框
      const confirmResult = await feedbackRef.value.showConfirm({
        title: '批量拣货确认',
        content: `确定要拣货这 ${validItems.length} 项商品吗？`,
        icon: 'icon-info',
        iconColor: '#165DFF'
      });
      
      if (!confirmResult) return;
    }
    
    submitting.value = true;
    
    // 生成唯一的消息ID
    const loadingMsgId = showLoadingMessage('正在处理批量拣货请求...', 2000);
    
    try {
      // 准备拣货数据 - 只使用有效的商品记录
      const pickData = {
        order_id: outboundId,
        items: validItems.map(detail => ({
          order_item_id: detail.id,
          location_id: detail.selectedLocation,
          picked_quantity: detail.pickedQuantity,
          note: detail.remark || '',
          batch_no: detail.batchNumber || '',
        }))
      };

      console.log('批量拣货提交数据:', pickData);

      // 调用API
      const result = await outboundStore.pickOutbound(outboundId, pickData);
      
      // 清除加载提示
      clearLoadingMessage(loadingMsgId);
      clearAllLoadingMessages();
      
      if (result) { // 假设 store action 成功时返回真值
        Message.success(`批量拣货 ${validItems.length} 项成功`); // 使用简单消息
        
        // 清空选择
        selectedRowKeys.value = [];
        
        // 显示数据刷新加载消息
        const refreshMsgId = showLoadingMessage('正在刷新数据...', 3000);
        
        // 延长等待时间，确保后端处理完成
        await new Promise(resolve => setTimeout(resolve, 800));
        
        // 重新获取数据，添加重试逻辑
        let retryCount = 0;
        const maxRetries = 2;
        
        while (retryCount <= maxRetries) {
          try {
            await getOutboundDetail();
            break; // 成功则跳出循环
          } catch (refreshError) {
            console.error(`刷新数据失败(尝试 ${retryCount + 1}/${maxRetries + 1}):`, refreshError);
            if (retryCount === maxRetries) {
              Message.error('数据刷新失败，请手动刷新页面');
            } else {
              // 等待后重试
              await new Promise(resolve => setTimeout(resolve, 500));
            }
            retryCount++;
          }
        }
        
        // 清除加载消息
        clearLoadingMessage(refreshMsgId);
      } else {
        // 失败情况已由 store 处理或在 catch 中处理
      }
    } catch (error) {
      console.error('批量拣货失败:', error);
      // 清除加载提示
      clearLoadingMessage(loadingMsgId);
      clearAllLoadingMessages();
      
      Message.error(error.message || '批量拣货失败');
    } finally {
      submitting.value = false;
      // 确保再次清除所有加载消息
      clearAllLoadingMessages();
    }
  } catch (error) {
    console.error('批量拣货操作错误:', error);
    Message.error('批量拣货操作发生错误');
    clearAllLoadingMessages();
  }
};

// 完成拣货
const completePicking = async () => {
  if (!canCompletePicking.value) {
    Message.warning('尚有未处理的商品，无法完成拣货');
    return;
  }
  
  // 先清除可能存在的加载消息
  clearAllLoadingMessages();
  
  try {
    // 显示确认对话框
    const confirmResult = await feedbackRef.value.showConfirm({
      title: '完成拣货',
      content: '确认完成本次拣货操作吗？完成后将转入发货环节。',
      icon: 'icon-info',
      iconColor: '#165DFF'
    });
    
    if (!confirmResult) return;
    
    submitting.value = true;
    
    // 生成唯一的消息ID
    const loadingMsgId = showLoadingMessage('正在完成拣货操作...', 2000);

    try {
      // 首先获取最新的出库单详情，确认当前状态
      const latestDetail = await outboundStore.getOutboundDetail(outboundId);
      
      if (latestDetail && latestDetail.status === 2) {
        // 如果已经是待发货状态，直接跳转
        clearLoadingMessage(loadingMsgId);
        Message.success('出库单已处于待发货状态，正在跳转到发货页面...');
        
        // 使用延时确保DOM操作完成后再跳转
        setTimeout(() => {
          router.push({
            name: 'ShippingOperation',
            params: { id: outboundId }
          });
        }, 300);
        return;
      }
      
      // 当前状态不是待发货，调用API更新状态
      const result = await outboundStore.updateOutboundStatus(outboundId, 2);
      
      // 清除加载提示
      clearLoadingMessage(loadingMsgId);
      clearAllLoadingMessages();
      
      if (result) {
        // 显示成功消息并跳转
        Message.success('拣货完成，订单状态已更新为待发货，即将跳转到发货页面...');
        
        // 使用延时确保DOM操作完成后再跳转
        setTimeout(() => {
          router.push({
            name: 'ShippingOperation',
            params: { id: outboundId }
          });
        }, 300);
      }
    } catch (error) {
      console.error('完成拣货失败:', error);
      
      // 检查错误消息，处理特定情况
      if (error.message && error.message.includes('待发货的出库单只能改为已完成或取消')) {
        // 特殊情况：出库单已经是待发货状态
        Message.info('出库单已处于待发货状态，正在跳转到发货页面...');
        
        // 使用延时确保DOM操作完成后再跳转
        setTimeout(() => {
          router.push({
            name: 'ShippingOperation',
            params: { id: outboundId }
          });
        }, 300);
      } else {
        // 其他错误
        Message.error(error.message || '完成拣货失败，请稍后重试');
      }
      
      clearLoadingMessage(loadingMsgId);
      clearAllLoadingMessages();
    }
  } catch (error) {
    console.error('完成拣货操作错误:', error);
    Message.error('完成拣货操作发生错误');
    clearAllLoadingMessages();
  } finally {
    submitting.value = false;
  }
};

// 获取出库单详情
const getOutboundDetail = async () => {
  try {
    loading.value = true;
    
    const result = await outboundStore.getOutboundDetail(outboundId);
    
    // Log the entire result object from the store
    console.log('Result from outboundStore.getOutboundDetail:', result);

    if (result) {
      outboundDetail.value = result; // Assign the whole result
      
      // Use result.items instead of result.details
      const items = result.items;
      
      // Log the raw items array (assuming it's result.items)
      console.log('Raw result.items from store:', items);

      // 处理详情列表数据，检查 items 是否存在且是数组
      if (items && Array.isArray(items) && items.length > 0) { 
        detailList.value = items.map(item => {
          // 准备数据进行判断
          const orderedQuantity = Number(item.quantity || 0);
          const backendPickedQuantity = Number(item.picked_quantity || 0); // 后端返回的已拣货数量
          const backendStatus = item.status?.toString().toLowerCase(); // 获取后端状态并转小写
          
          // 增强判断是否已拣货的逻辑 (状态判断 + 数量判断)
          const statusPicked = ['picked', 'shipping', 'completed', '2', '3'].includes(backendStatus) || item.status === 2 || item.status === 3; 
          const quantityPicked = backendPickedQuantity > 0 && backendPickedQuantity >= orderedQuantity;
          const isPicked = statusPicked || quantityPicked;
          
          console.log(`商品 ${item.cargo?.name || '未知'} 拣货状态判断:`, {
            id: item.id,
            orderedQuantity,
            backendPickedQuantity,
            backendStatus,
            statusPicked,
            quantityPicked,
            isPicked
          });
          
          // 返回映射后的对象
          return {
            ...item,
            productId: item.cargo_id, 
            specification: item.specification || item.spec || (item.cargo?.spec || item.cargo?.specification || '-'), 
            unit: item.cargo?.unit || '-', 
            productCode: item.cargo?.code || '-', 
            productName: item.cargo?.name || '-', 
            quantity: orderedQuantity, // 使用处理过的订单数量
            selectedLocation: null, // 初始不选择库位，待 loadProductLocations 设置或用户选择
            pickedQuantity: isPicked ? backendPickedQuantity : orderedQuantity, // 已拣货使用后端数量，否则默认为订单数量
            availableLocations: [],
            maxPickable: 0, // 将由 loadProductLocations 更新
            picked: isPicked, // 使用组合逻辑判断的结果
            status: isPicked ? 2 : (typeof item.status === 'number' ? item.status : 1), // 使用数字状态：2=待发货（已拣货），1=待拣货（默认）
            selectedLocationInfo: null // 初始化显示对象
          };
        });
        
        // Log the processed list
        console.log('Processed detailList with improved picked logic:', detailList.value);
        
        await loadProductLocations(); // 这个函数需要确保不会覆盖 pickedQuantity
      } else {
        detailList.value = [];
        console.log('result.items is empty, null, or not an array, setting detailList to empty array.');
      }
    } else {
       console.log('getOutboundDetail returned null or undefined result.');
       detailList.value = []; 
    }
  } catch (error) {
    console.error('获取出库单详情失败:', error);
    Message.error('获取出库单详情失败');
    detailList.value = []; 
  } finally {
    loading.value = false;
  }
};

// 获取库位名称
const getLocationNameById = (locationId) => {
  if (!locationId) return '未选择';
  
  // 遍历所有商品的可用库位列表，查找匹配的库位
  for (const item of detailList.value) {
    const location = item.availableLocations.find(loc => loc.id === locationId);
    if (location) {
      return location.name;
    }
  }
  
  return '未知库位';
};

// 重置行选择，确保选择状态和UI保持一致
const resetRowSelection = () => {
  // 确保是数组
  ensureSelectedKeysIsArray();
  
  // 清空选择
  selectedRowKeys.value = [];
  
  // 检查可选择行的数量
  const selectableRows = detailList.value.filter(item => !item.picked);
  console.log(`共有 ${detailList.value.length} 行, 其中 ${selectableRows.length} 行可选择`);
};

// 刷新选择状态
const refreshSelection = () => {
  console.log('刷新选择状态...');
  
  // 确保selectedRowKeys.value是数组
  if (!Array.isArray(selectedRowKeys.value)) {
    selectedRowKeys.value = [];
  }
  
  // 检查DOM中实际选中的checkbox
  const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
  console.log('页面中选中的checkbox数量:', checkboxes.length);
  
  if (checkboxes.length === 0) {
    // 如果没有选中项，清空选择
    if (selectedCount.value > 0) {
      console.log('清空选择状态');
      selectedRowKeys.value = [];
    }
    Message.info('没有检测到选中项');
    return;
  }
  
  // 收集选中的行
  const selectedIds = [];
  let foundMismatch = false;
  
  // 跳过第一个checkbox(可能是全选框)
  for (let i = 1; i < checkboxes.length; i++) {
    const checkbox = checkboxes[i];
    const rowIndex = i - 1; // 减1因为跳过了全选框
    
    if (rowIndex < detailList.value.length) {
      const rowId = detailList.value[rowIndex].id;
      selectedIds.push(rowId);
      
      // 检查是否与当前selectedRowKeys一致
      if (!selectedRowKeys.value.includes(rowId)) {
        foundMismatch = true;
      }
    }
  }
  
  if (foundMismatch || selectedCount.value !== selectedIds.length) {
    console.log('更新选择状态:', selectedIds);
    selectedRowKeys.value = selectedIds;
    Message.success(`已更新选择状态，当前选中 ${selectedIds.length} 项`);
  } else {
    Message.info(`当前选中 ${selectedIds.length} 项，无需更新`);
  }
  
  // 批量设置所有选中项的库位和拣货数量（如果未设置）
  for (const itemId of selectedRowKeys.value) {
    const record = detailList.value.find(item => item.id === itemId);
    if (!record) continue;
    
    // 如果没有选择库位，自动选择第一个有库存的库位
    if (!record.selectedLocation && record.availableLocations && record.availableLocations.length > 0) {
      const availableLoc = record.availableLocations.find(loc => loc.hasStock);
      if (availableLoc) {
        console.log(`自动为商品 ${record.productName} 选择库位:`, availableLoc);
        record.selectedLocation = availableLoc.id;
        record.maxPickable = availableLoc.available;
        
        // 如果拣货数量未设置或为0，设置为订单数量与可用数量的较小值
        if (!record.pickedQuantity || record.pickedQuantity <= 0) {
          record.pickedQuantity = Math.min(record.quantity, availableLoc.available);
          console.log(`自动设置商品 ${record.productName} 拣货数量:`, record.pickedQuantity);
        }
      }
    }
  }
};

// 页面加载时获取数据
onMounted(async () => {
  // 确保选择状态正确初始化
  ensureSelectedKeysIsArray();
  
  if (!outboundId) {
    Message.error('缺少出库单ID参数');
    router.push('/outbound/orders');
    return;
  }
  
  // 确保清除之前可能存在的所有加载消息
  clearAllLoadingMessages();
  
  try {
    await getOutboundDetail();
    // 重置选择状态
    resetRowSelection();
    
    // 添加表格选择变化的额外监听（防止常规事件不触发）
    document.querySelectorAll('table').forEach(table => {
      table.addEventListener('change', () => {
        console.log('检测到表格checkbox变化');
        setTimeout(() => autoRefreshSelection(), 50);
      });
    });
    
    // 启动自动检测选择状态
    startAutoSelectionCheck();
    console.log('已启动自动选择状态检测');
  } catch (error) {
    console.error('页面加载失败:', error);
  }
});

// 组件卸载前清理
onBeforeUnmount(() => {
  // 清除定时器
  if (selectionCheckTimer) {
    clearInterval(selectionCheckTimer);
    selectionCheckTimer = null;
    console.log('已清理选择状态检测定时器');
  }
  
  // 清除所有加载消息
  clearAllLoadingMessages();
});
</script>

<style scoped>
.container {
  padding: 0 16px 16px;
}

.general-card {
  margin-top: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.step-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 16px;
}

.picking-area {
  margin-top: 24px;
}

.action-bar {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.variance-positive {
  color: #00b42a;
  font-weight: bold;
}

.variance-negative {
  color: #f53f3f;
  font-weight: bold;
}

.variance-normal {
  color: #86909c;
}
</style>